import { Injectable } from '@angular/core';
import {FileInfo} from "../model/file-info";
// import * as Path from "path";

@Injectable({
  providedIn: 'root'
})
export class SystemUtilsService {
  // nodePath = require('path')
  // nodeFs = require('fs/promises')
  nodePath:any
  nodeFs:any
  infoLog:string[]= []
  debugLog:string[]= []
  constructor() {
    // import * as fs from 'fs/promises';
    // @ts-ignore
    this.nodePath = window.nodeApi.path;
    // @ts-ignore

    this.nodeFs = window.nodeApi.fs;
  }

  public getFileName(path:string):string{
    return this.nodePath.basename(path)
  }
  public getFileExt(path:string):string{
    return this.nodePath.extname(path)
  }
  public getFileDir(path:string):string{
    return this.nodePath.dirname(path)
  }
  public pathJoin(path:string[]):string{
    return this.nodePath.join(path)
  }

  public async readFile(path: string) {
    return await this.nodeFs.readFile(path)
  }

  public async getFileInfoData(fileInfo:FileInfo){
    if (fileInfo.fileData == null){
      let data =await this.readFile(fileInfo.filePath)
      fileInfo.fileData = data
    }
    return fileInfo.fileData;
  }

  public getPromisesFs(){
    return this.nodeFs;
  }
  public async moveFile(fileInfo:FileInfo,targetPath:string){
    return await this.nodeFs.rename(fileInfo.filePath,targetPath)
  }
  public async copyFile(fileInfo:FileInfo,targetPath:string,exitCancel:boolean){
    if (exitCancel){
      return await this.nodeFs.copyFile(fileInfo.filePath,targetPath,1)
    }else{
      return await this.nodeFs.copyFile(fileInfo.filePath,targetPath)
    }

  }

  public info(...data: any[]){
    this.debug(data)

  }
  public debug(...data: any[]){
    console.info(data)

    this.infoLog.push(   data.map((it: any) => {
      if (typeof it == "object"){
        return JSON.stringify(it)
      }
      return it
    }).join(" "))
  }
  public cleanLog(){
    this.debugLog=[]
    this.infoLog=[]
  }
}
